package com.white.commonlib.engine;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by yutf on 2017/5/12 0012.
 */

public class CutDownner
{

    private Context mCtx;
    private int s;
    private int staticValue;
    private Handler mHandler = new Handler(Looper.getMainLooper())
    {
        @Override
        public void handleMessage(Message msg)
        {
            if(call != null)
            {
                call.onCutdowing(s);
            }
        }
    };
    private Timer timer;
    private TimerTask task;
    private boolean isRunning;
    private Callback call;
    public CutDownner(int second)
    {
        s = second;
        staticValue = second;
    }

    public void start(Callback c)
    {
        call = c;
        s = staticValue;
        if(call != null)
        {
            call.onStart(s);
        }
        reset();
        timer = new Timer();
        task = new CutTask();
        timer.scheduleAtFixedRate(task, 0,1000);
        isRunning = true;
    }

    private void reset()
    {
        if(timer != null && task != null)
        {
            timer.cancel();
            task.cancel();
            timer = null;
            task = null;
        }
    }

    public boolean isRunning()
    {
        return isRunning;
    }

    public void recycle()
    {
        reset();
        s = staticValue;
    }

    private class CutTask extends TimerTask
    {
        @Override
        public void run()
        {
            mHandler.sendEmptyMessage(0);
            s = s-1;
            if(s == 0)
            {
                s = staticValue;
                isRunning = false;
                recycle();
                if(call != null)
                {
                    mHandler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            call.onComplete();
                        }
                    });
                }
            }
        }
    }

    public interface Callback
    {
        void onStart(int seconds);
        void onCutdowing(int seconds);
        void onComplete();
    }
}
